package com.yint.server.state;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ThreadPoolExecutor;

import com.yint.core.Handler;

public class ReadState implements HandlerState {

	@Override
	public void handle(Handler h, SelectionKey sk, SocketChannel sc, ThreadPoolExecutor pool) throws IOException {
		// non-blocking下不可用Readers，因为Readers不支持non-blocking
		byte[] arr = new byte[1024];
		ByteBuffer buf = ByteBuffer.wrap(arr);
		int numBytes = sc.read(buf); // 读取字符串
		if (numBytes == -1) {
			System.out.println("[Warning!] A client has been closed.");
			h.close();
			return;
		}
		// 将读取到的byte内容转换成字符串
		String str = new String(arr);
		if ((str != null) && !str.equals(" ")) {
			// 改变状态(READING->WORKING)
			h.changeState(new WorkState());
			pool.execute(new WorkerThread(h,sk, str)); // do process in worker thread
			System.out.println(sc.socket().getRemoteSocketAddress().toString() + " > " + str);
		}
	}

	/**
	 * 执行处理逻辑
	 * 
	 * @param h
	 * @param str
	 */
	synchronized void process(Handler h,SelectionKey sk, String str) {
		// 改变状态(WORKING->SENDING
		h.changeState(new WriteState());
		// 通过key在编通道注册的事件
		sk.interestOps(SelectionKey.OP_WRITE);
		// 使一个阻塞住的selector操作立即返回
		sk.selector().wakeup();
	}

	/**
	 * 工作线程
	 * 
	 * @author yintian
	 *
	 */
	class WorkerThread implements Runnable {

		Handler h;
		String str;
		SelectionKey sk;

		public WorkerThread(Handler h,SelectionKey sk, String str) {
			this.h = h;
			this.str = str;
			this.sk=sk;
		}

		@Override
		public void run() {
			process(h,sk, str);
		}

	}

}
